package web.gkw.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Component;

import web.gkw.model.General;
import web.gkw.model.Technique;
import web.gkw.model.User;
import web.gkw.service.GeneralService;
import web.gkw.service.TechniqueService;
import web.gkw.service.UserService;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

@Component
public class Index extends ActionSupport {
	
	@Resource
	private UserService userService;
	private Map session;

	public Map getSession() {
		return session;
	}


	public void setSession(Map session) {
		this.session = session;
	}


	public UserService getUserService() {
		return userService;
	}


	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	@Override
	public String execute() throws Exception {
		// TODO Auto-generated method stub
		ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpServletResponse response = ServletActionContext.getResponse();
		PrintWriter out = response.getWriter();
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		User user = (User)ctx.getBean("user");
		user.setUsername(username);
		user.setPassword(password);
		User res = userService.login(user);
		ActionContext ctx2 =ActionContext.getContext();
		session = ctx2.getSession();
		if(res != null) {
			session.put("user", res);
			out.println(true);
		}else {
			out.println(false);
		}
		out.flush();
		out.close();
		return "success";
	}
	
	public String logout() {
		System.out.println(session == null);
		ActionContext ctx2 =ActionContext.getContext();
		HttpServletResponse response = ServletActionContext.getResponse();
		PrintWriter out = null;
		try {
			out = response.getWriter();
			session = ctx2.getSession();
			if(session!= null) {
				System.out.println(session.containsKey("user"));
				if(session.containsKey("user")) {
					session.remove("user");
					System.out.println("user has been remove from session...");
					out.println(true);
				}else {
					out.println(false);
				}
			}else {
				out.println(false);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
}
